import 'dart:async';
import 'package:inmotion_pro/extension/future_error_handler.dart';
import 'package:inmotion_pro/l10n/local.dart';
import 'package:inmotion_pro/pages/mixin/bluetooth_mixin.dart';
import 'package:inmotion_pro/pages/mixin/cache_mixin.dart';
import 'package:inmotion_pro/pages/mixin/vehicle_type_mixin.dart';
import 'package:ble_helper_plugin/library.dart';
import 'package:get/get.dart';
import 'package:lx_widgets_library/lx_widgets_library.dart';
import '../mixin/bluetooth_permission_mixin.dart';
import 'state.dart';

// 蓝牙搜索控制器
class BleSearchController extends GetxController
    with
        CacheMixin,
        BluetoothPermissionMixin,
        BluetoothMixin,
        VehicleTypeMixin {
  // 状态
  BleSearchState state = BleSearchState();

  // 延迟300毫秒开始扫描
  final int delayTimeToScan = 500;

  // 蓝牙适配器状态监听
  StreamSubscription<CustomBluetoothAdapterState>? _bluetoothAdapterState;

  @override
  void onInit() {
    super.onInit();

    // 检测蓝牙权限
    _bluetoothAdapterState = bluetoothPermissionBluetoothPermission(
      onSuccess: () {
        // 开始扫描
        _scan();
      },
      onFailed: () {
        bluetoothMixinStopScan();
      },
    );
  }

  @override
  void onClose() async {
    _bluetoothAdapterState?.cancel();
    await bluetoothMixinStopScan();
    super.onClose();
  }

  // 开始连接
  connectDeviceOnTap(CustomScanResult scanResult) {
    Loading.showLoading(local.connecting);
    bluetoothMixinConnectScanResult(scanResult).then((connectSuccess) {
      if (connectSuccess) {
        // 连接成功
        state.bluetoothConnectState.value =
            CustomBluetoothConnectState.connected;
        Get.back();
      } else {
        // 连接失败
        Loading.showToast(local.ble_connect_failed);
      }
    }).catchErrorHandler();
  }

  // 重新扫描
  Future<void> searchAgainOnTap() async {
    _scan();
  }

  // 扫描
  _scan() async {
    state.scanResults.value = null;
    state.scanResults.refresh();
    await bluetoothMixinStopScan();
    await Future.delayed(Duration(milliseconds: delayTimeToScan));
    bluetoothMixinStartScan((results) {
      // 过滤results中设备名称不符合的设备
      results = results.where((result) {
        return vehicleTypeMixinIsValidVehicleName(
            bleName: result.device.advName);
      }).toList();
      state.scanResults.value = results;
      state.scanResults.refresh();
    }, timeout: const Duration(seconds: 30));
  }
}
